/**
 * 模型发现服务 - 动态获取和管理可用模型
 */
import { message } from 'antd';

const API_BASE = import.meta.env.VITE_API_URL || import.meta.env.REACT_APP_API_URL || 'http://localhost:8002';

// 模型能力接口
export interface ModelCapabilities {
  maxTokens: number;
  supportsStreaming: boolean;
  supportsFunctionCalling: boolean;
  supportsVision: boolean;
  contextWindow: number;
}

// 可用模型接口
export interface AvailableModel {
  id: string;
  name: string;
  displayName: string;
  provider: string;
  providerName: string;
  baseUrl: string;
  status: 'available' | 'unavailable' | 'checking' | 'unknown';
  capabilities: ModelCapabilities;
  lastChecked?: Date;
  responseTime?: number;
  errorMessage?: string;
  version?: string;
  recommended?: boolean;
}

// 模型发现响应接口
export interface ModelDiscoveryResponse {
  models: AvailableModel[];
  lastRefresh: Date;
  cacheTtl: number;
}

// 模型发现结果接口
export interface ModelDiscoveryResult {
  success: boolean;
  models: any[];
  error?: string;
}

class ModelDiscoveryService {
  private cache: Map<string, { data: AvailableModel[]; expiry: number }> = new Map();
  private subscribers: Set<(models: AvailableModel[]) => void> = new Set();
  private refreshInterval: NodeJS.Timeout | null = null;
  
  constructor() {
    // 禁用定期刷新 - 改用 model-config.service
    // this.startAutoRefresh();
  }
  
  /**
   * 获取可用模型列表
   * @deprecated 请使用 model-config.store 替代
   */
  async getAvailableModels(forceRefresh = false): Promise<AvailableModel[]> {
    // 此服务已弃用，请使用 useModelConfigStore().configs
    console.warn('[ModelDiscoveryService] This service is deprecated. Use useModelConfigStore().configs instead.');

    // 返回空数组，避免404错误
    return [];
  }
  
  /**
   * 主动发现特定提供商的模型
   */
  async discoverModels(
    provider: string,
    baseUrl: string,
    apiKey: string
  ): Promise<ModelDiscoveryResult> {
    try {
      const response = await fetch(`${API_BASE}/models/discover`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({ provider, baseUrl, apiKey })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.success) {
        message.success(`发现 ${result.models.length} 个可用模型`);
      } else {
        message.error(result.error || '模型发现失败');
      }
      
      return result;
    } catch (error) {
      console.error('Failed to discover models:', error);
      message.error('模型发现失败');
      return {
        success: false,
        models: [],
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }
  
  /**
   * 检查特定模型的健康状态
   */
  async checkModelHealth(modelId: string): Promise<any> {
    try {
      const response = await fetch(`${API_BASE}/models/health/${modelId}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error(`Failed to check health for model ${modelId}:`, error);
      return {
        status: 'unavailable',
        error: error instanceof Error ? error.message : '健康检查失败'
      };
    }
  }
  
  /**
   * 批量检查模型健康状态
   */
  async batchCheckModelHealth(modelIds: string[]): Promise<Record<string, any>> {
    const results: Record<string, any> = {};
    
    // 并发检查所有模型
    const promises = modelIds.map(async (modelId) => {
      const health = await this.checkModelHealth(modelId);
      results[modelId] = health;
    });
    
    await Promise.all(promises);
    
    return results;
  }
  
  /**
   * 刷新模型缓存
   */
  async refreshCache(): Promise<void> {
    try {
      const response = await fetch(`${API_BASE}/models/refresh-cache`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.success) {
        message.success('模型缓存已刷新');
        // 重新获取模型列表
        await this.getAvailableModels(true);
      }
    } catch (error) {
      console.error('Failed to refresh cache:', error);
      message.error('缓存刷新失败');
    }
  }
  
  /**
   * 订阅模型更新
   */
  subscribeToModelUpdates(callback: (models: AvailableModel[]) => void): () => void {
    this.subscribers.add(callback);
    
    // 立即发送当前模型列表
    this.getAvailableModels().then(models => callback(models));
    
    // 返回取消订阅函数
    return () => {
      this.subscribers.delete(callback);
    };
  }
  
  /**
   * 通知所有订阅者
   */
  private notifySubscribers(models: AvailableModel[]): void {
    this.subscribers.forEach(callback => {
      try {
        callback(models);
      } catch (error) {
        console.error('Error in model update subscriber:', error);
      }
    });
  }
  
  /**
   * 启动自动刷新
   */
  private startAutoRefresh(): void {
    // 每5分钟刷新一次
    this.refreshInterval = setInterval(() => {
      this.getAvailableModels(false).catch(error => {
        console.error('Auto refresh failed:', error);
      });
    }, 5 * 60 * 1000);
  }
  
  /**
   * 停止自动刷新
   */
  stopAutoRefresh(): void {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
      this.refreshInterval = null;
    }
  }
  
  /**
   * 获取推荐模型
   */
  async getRecommendedModels(): Promise<AvailableModel[]> {
    const models = await this.getAvailableModels();
    return models.filter(model => model.recommended);
  }
  
  /**
   * 按提供商获取模型
   */
  async getModelsByProvider(provider: string): Promise<AvailableModel[]> {
    const models = await this.getAvailableModels();
    return models.filter(model => model.provider.toLowerCase() === provider.toLowerCase());
  }
  
  /**
   * 获取可用的模型（状态为available）
   */
  async getOnlineModels(): Promise<AvailableModel[]> {
    const models = await this.getAvailableModels();
    return models.filter(model => model.status === 'available');
  }
  
  /**
   * 搜索模型
   */
  async searchModels(query: string): Promise<AvailableModel[]> {
    const models = await this.getAvailableModels();
    const lowerQuery = query.toLowerCase();
    
    return models.filter(model => 
      model.name.toLowerCase().includes(lowerQuery) ||
      model.displayName.toLowerCase().includes(lowerQuery) ||
      model.provider.toLowerCase().includes(lowerQuery) ||
      model.providerName.toLowerCase().includes(lowerQuery)
    );
  }
  
  /**
   * 获取模型统计信息
   */
  async getModelStatistics(): Promise<{
    total: number;
    available: number;
    unavailable: number;
    checking: number;
    providers: Record<string, number>;
  }> {
    const models = await this.getAvailableModels();
    
    const stats = {
      total: models.length,
      available: 0,
      unavailable: 0,
      checking: 0,
      providers: {} as Record<string, number>
    };
    
    models.forEach(model => {
      // 统计状态
      switch (model.status) {
        case 'available':
          stats.available++;
          break;
        case 'unavailable':
          stats.unavailable++;
          break;
        case 'checking':
          stats.checking++;
          break;
      }
      
      // 统计提供商
      if (model.provider) {
        stats.providers[model.provider] = (stats.providers[model.provider] || 0) + 1;
      }
    });
    
    return stats;
  }
  
  /**
   * 获取认证令牌
   */
  private getAuthToken(): string {
    return localStorage.getItem('authToken') || '';
  }
}

// 导出单例
export default new ModelDiscoveryService();